var crypto = require('crypto');
var request = require('request');
var DBFactory = require('../db/mysql_db');
(function() {

    var PKG = this.PKG = function(payload) {
        this.status = 200;
        this.payload = remove_empty(payload);
    }

    var ERR = this.ERR = function(msg, status) {
        this.status = status ? status : 500;
        this.err = msg;
        console.log(msg);
    }

    var paramAll = this.paramAll = function (req) {
        var parameter = {};
        if(req.params)  for(var k in req.params) parameter[k] = req.params[k];
        if(req.query)  for(var k in req.query) parameter[k] = req.query[k];
        if(req.body)  for(var k in req.body) parameter[k] = req.body[k];
        return parameter;
    };

    var simpleDateFormat = this.simpleDateFormat = function (time, onlyDate) {
        var d = new Date(time);
        var month = d.getMonth() + 1;
        if (month < 10) month = '0' + month;
        var date = d.getDate();
        if (date < 10) date = '0' + date;
        var hour = d.getHours();
        if (hour < 10) hour = '0' + hour;
        var minute = d.getMinutes();
        if (minute < 10) minute = '0' + minute;
        var second = d.getSeconds();
        if (second < 10) second = '0' + second;
        if(onlyDate) return d.getFullYear() + '-' + month + '-' + date ;
        return d.getFullYear() + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
    };

    var encryPassword = this.encryPassword = function (password) {
        password = 'hello' + password;
        var md5 = crypto.createHash('md5');
        md5.update(password);
        password = md5.digest('hex');
        return password;
    };

    Date.prototype.format = function(fmt) {
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    }

    var checkHasParam = this.checkHasParam = function (param, needParams) {
        for (var i = 0; i < needParams.length; i++) {
            var needParam = needParams[i];
            if (param[needParam] == undefined || param[needParam] == null || param[needParam] == '') {
                var err = '参数有误：' + needParam + '不为空';
                return {err:err};
            }
        }
        return {err:null};
    }

    var customRequest = this.customRequest = function (opt, callback) {
        request(opt, function(error, response, body) {
            if(error || !body) {
                console.log(error);
                return callback('访问出错！');
            } else {
                try {
                    body = JSON.parse(body);
                    callback(null, body);
                } catch (e) {
                    console.log(e);
                    callback(e);
                }
            }
        })
    }

    var getIp4 = this.getIp4 = function(ip) {
        if (ip.length > 15) ip = ip.slice(7);
        return ip;
    };

    var remove_empty = this.remove_empty = function(target) {
        if (!(target instanceof Object)) return target;
        Object.keys( target ).map( function ( key ) {
            if ( target[ key ] instanceof Object ) {
                if ( ! Object.keys( target[ key ] ).length && typeof target[ key ].getMonth !== 'function') {
                    delete target[ key ];
                } else {
                    remove_empty( target[ key ] );
                }
            } else if ( target[ key ] === null ) {
                delete target[ key ];
            }
        } );
        return target;
    };

    var randomString = this.randomString = function (len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    };

    var vipEndTime = this.vipEndTime = function (endTime) {
        var now = new Date();
        var end_time = new Date(endTime);
        var day = ( end_time.getTime() - now.getTime() ) /(1000*60*60*24);
        end_time = end_time.getTime();
        end_time = new Date(end_time);
        var info = (day > 0) ? {can_use:1, vip_end_time:end_time} : {can_use:0,vip_end_time:end_time};
        return info ;
    }

    //将推荐码转为uid
    var codeToUid = this.codeToUid = function(str) {
        var myreg = /^[A-Z0-9]*$/;
        if (myreg.test(str)) {
            return newCodeToUid(str);
        }
        var set = 'hjklzxcvbnmopasdfgqwertyui';
        var a = str.toLocaleLowerCase().split('');
        var index5 = set.indexOf(a[0]);
        var index1 = set.indexOf(a[1]);
        var index2 = set.indexOf(a[2]);
        var index3 = set.indexOf(a[3]);
        var index4 = set.indexOf(a[4]);
        var verifyCode = (index1 + index2 + index3 + index4) % 26;

        if (verifyCode == index5) {
            var uid = index1 + index2 * 26 + index3 * 26 * 26 + index4 * 26 * 26 * 26 + 1;
            return uid;
        } else {
            return false;
        }
    };

    var newCodeToUid = this.newCodeToUid = function(str) {
        if (typeof (str) != 'string') return false;
        var toCodeObj = { '0': 'Z','1': '2','2': 'P','3': 'J','4': '5',
            '5': 'L', '6': '3','7': 'Q','8': '1','9': 'A',O:'0',J:'4',
            U:'6',P:'7',F:'8',V:'9',R:'B',Z:'C',L:'D',H:'E',Q:'F',E:'G',
            I:'H',K:'I',M:'K',T:'M',Y:'N',C:'O',B:'R',N:'S',A:'T',G:'U',
            S:'V',D:'Y' };
        var realStr = '';
        for (var i = 0; i < str.length; i++) {
            var char = str.charAt(i);
            var realChar = toCodeObj[char];
            realStr += realChar;
        }
        var uid = parseInt(realStr,32);
        return uid;
    };

    //uid生成推荐码 注意，修改时usuz_srv也要改  新版的code 大小写有区分  440000之前都是小写字母  之后变为数字加大写字母
    var uidToCode = this.uidToCode = function (uid) {
        if (uid > 440000) {
            return newUidToCode(uid);
        }
        var set ='hjklzxcvbnmopasdfgqwertyui';
        var index1;
        var index2;
        var index3;
        var index4;
        var index5;
        var merchant = parseInt(uid)-1;

        index1 = merchant % 26;
        index2 = parseInt(merchant/26);
        index3 = 0;
        index4 = 0;

        if(index2 >= 26) {
            index3 = parseInt(index2 / 26);
            index2 = index2 % 26;
            if(index3 >= 26) {
                index4 = parseInt(index3 / 26);
                index3 = index3 % 26;
            }
        }
        index5 = (index1 + index2 + index3 + index4) % 26;
        var str = set[index5] + set[index1] + set[index2] + set[index3] + set[index4];
        return str;
    }

    var newUidToCode = this.newUidToCode = function (uid) {
        //判断uid是不是数字
        if (typeof (uid) != 'number') return false;
        var codeToObj = {'0':'O','1':'8', '2':'1', '3':'6','4':'J','5':'4','6':'U','7':'P','8':'F','9':'V',
            A:'9',B:'R',C:'Z',D:'L', E:'H',F:'Q',G:'E',H:'I',I:'K',J:'3',K:'M',L:'5',M:'T',N:'Y',O:'C',
            P:'2',Q:'7',R:'B',S:'N',T:'A', U:'G',V:'S',Y:'D',Z:'0',
        };
        uid = parseInt(uid);
        var waitStr = uid.toString(32).toUpperCase(); //转换为32进制字符串
        var code = '';
        for (var i = 0; i < waitStr.length; i++) {
            var char = waitStr.charAt(i);
            code += codeToObj[char];
        }
        return code;
    };
})();